package com.mango.acat.core.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.mango.acat.core.server.netty.NettyServer;
import com.mango.acat.core.setting.AppSetting;
import com.xiaoleilu.hutool.lang.Singleton;

public class HttpServer implements Runnable {
	private static Logger _log = Logger.getLogger(HttpServer.class);
	private final int port;
	private final String serverClass;
	private static IServer _server;

	public HttpServer() {
		this.port = AppSetting.app.getInt("app.port", 80);
		this.serverClass = AppSetting.app.getStr("app.server.class",NettyServer.class.getName());
	}

	public HttpServer(int port) throws Exception {
		this.serverClass = AppSetting.app.getStr("app.server.class",NettyServer.class.getName());
		this.port = port;
		if (isPortUsing("127.0.0.1", port)) {
			throw new Exception("端口号：" + port + "已经被占用，服务将强制退出。");
		}
	}

	public HttpServer(int port, String serverClass) {
		this.port = port;
		this.serverClass = serverClass;
	}

	public void run() {
		_log.info("初始化IServer[" + this.serverClass + "]应用...");

		_server = (IServer) Singleton.get(this.serverClass);
		if (_server != null) {
			_server.start(this.port);
		}
	}

	public static void restart() {
		if (_server != null) {
			_server.restart();
		}
	}

	public static void main(String[] args) throws Exception {
		new HttpServer(8080).run();
	}

	public static boolean isPortUsing(String host, int port) {
		boolean flag = false;
		Socket socket = null;
		try {
			InetAddress theAddress = InetAddress.getByName(host);
			socket = new Socket(theAddress, port);
			if ("noexecute".equals("0")) {
				socket.close();
			}
			flag = true;
		} catch (IOException localIOException) {
		}
		return flag;
	}
}
